<template>
  <div class="app-container">

    <!-- 设备搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <!-- 根据设备id搜索 -->
      <el-form-item label="设备ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 根据设备名称搜索 -->
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 根据所属产品搜索 -->
      <el-form-item label="所属产品" prop="productId">
        <el-select v-model="queryParams.productId" placeholder="请选择所属产品" clearable>
          <el-option
            v-for="dict in productList"
            :key="dict.id"
            :label="dict.productName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <!-- 搜索操作：搜索、重置 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <!-- 操作区域 -->
    <el-row :gutter="10" class="mb8">

      <!-- 新增设备 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:device:add']"
        >新增
        </el-button>
      </el-col>

      <!-- 激活设备 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-finished"
          size="mini"
          @click="batchDeployDevice"
          v-hasPermi="['iot:device:edit']"
        >激活
        </el-button>
      </el-col>

      <!-- 同步设备状态 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSyncDeviceState"
          v-hasPermi="['iot:device:edit']"
        >同步状态
        </el-button>
      </el-col>

      <!-- 绑定子设备 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-connection"
          size="mini"
          @click="bindChildrenDevice"
          v-hasPermi="['iot:device:edit']"
        >绑定子设备
        </el-button>
      </el-col>

      <!-- 解绑子设备 -->
      <el-col :span="3">
        <el-button
          type="warning"
          plain
          icon="el-icon-link"
          size="mini"
          :disabled="multiple"
          @click="unbindChildrenDevice"
          v-hasPermi="['iot:device:edit']"
        >解绑
        </el-button>
      </el-col>

      <!-- 设备状态数量统计 -->
      <!-- 设备总数 -->
      <el-col :span="3">
        <span class="device-state">全部设备&emsp;</span>
        <span>{{ this.count.amount }}</span>
      </el-col>

      <!-- 设备在线数量 -->
      <el-col :span="3">
        <svg-icon style="color: #45c904" icon-class="dot"/>
        <span class="device-state">在线&emsp;</span>
        <span>{{ this.count.onlineCount }}</span>
      </el-col>

      <!-- 设备离线数量 -->
      <el-col :span="3">
        <svg-icon style="color: red" icon-class="dot"/>
        <span class="device-state">离线&emsp;</span>
        <span>{{ this.count.offlineCount }}</span>
      </el-col>

      <!-- 设备未激活数量 -->
      <el-col :span="1.5">
        <svg-icon style="color: #1890ff" icon-class="dot"/>
        <span class="device-state">未激活&emsp;</span>
        <span>{{ this.count.notActiveCount }}</span>
      </el-col>

      <!-- 工具栏：隐藏显示搜索按钮、刷新按钮 -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="handleRefresh"></right-toolbar>

    </el-row>

    <!-- 设备列表 -->
    <el-table ref="deviceTable" v-loading="loading" :data="childrenDeviceList" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="设备ID" align="center" prop="id"/>

      <el-table-column label="设备名称" align="center" prop="deviceName"/>

      <el-table-column prop="productId" label="产品名称" header-align="center" align="center">
        <template slot-scope="scope">
            <span v-for="(item, index) in productList" :key="index" v-if="scope.row.productId === item.id">
              {{ item.productName }}
            </span>
        </template>
      </el-table-column>

      <el-table-column label="注册日期" sortable align="center" prop="registryTime"/>

      <el-table-column label="状态" align="center" prop="deviceState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_device_state" :value="scope.row.deviceState"/>
        </template>
      </el-table-column>

      <el-table-column label="描述" align="center" prop="description"/>

      <el-table-column label="操作" align="center" min-width="100px">

        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleCheck(scope.row)"
            v-hasPermi="['iot:device:list']"
          >查看
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:device:edit']"
          >修改
          </el-button>

          <el-button
            v-if="scope.row.deviceState === 'notActive'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:device:remove']"
          >删除
          </el-button>

          <el-button
            v-if="scope.row.deviceState === 'notActive'"
            size="mini"
            type="text"
            icon="el-icon-switch-button"
            @click="handleEnableDisableStateChange(scope.row)"
            v-hasPermi="['iot:device:edit']"
          >启用
          </el-button>

          <el-button
            v-if="scope.row.deviceState !== 'notActive'"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleEnableDisableStateChange(scope.row)"
            v-hasPermi="['iot:device:edit']"
          >禁用
          </el-button>

          <el-button
            v-if="scope.row.deviceState === 'notActive'"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="unbindChildrenDevice(scope.row)"
            v-hasPermi="['iot:device:remove']"
          >解绑
          </el-button>

        </template>

      </el-table-column>

    </el-table>

    <!-- 表格分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <children-device-add-edit ref="childrenDeviceAddEdit" @update="handleRefresh"/>

    <!--绑定子设备对话框-->
    <bind-children-device ref="bindChildrenDevice" @update="handleRefresh"/>

  </div>

</template>

<script>
  import { mapState } from 'vuex'
  import {
    listDevice,
    delDevice,
    deployDevice,
    undeployDevice,
    unbindChildrenDevice,
    queryDevice,
    syncDeviceState,
  } from '@/api/iot/device'
  import { queryProduct } from '@/api/iot/product'
  import ChildrenDeviceAddEdit from '@/views/iot/device/children/childrenDeviceAddEdit'
  import BindChildrenDevice from '@/views/iot/device/children/bindChildrenDevice'
  export default {
    name: 'ChildrenDevice',

    components: {
      ChildrenDeviceAddEdit,
      BindChildrenDevice
    },

    // 字典
    dicts: [
      'iot_device_state'
    ],

    computed: {
      ...mapState({
        deviceDetailInfo: state => state.device.deviceDetailInfo,
        tabsActiveName: state => state.device.tabsActiveName,
        detailedPageVisible: state => state.device.detailedPageVisible,
        deviceOnlineChange: state => state.device.deviceOnlineChange,
      }),
    },

    watch: {

      /** 监听页签变化*/
      tabsActiveName(tagName) {
        if (tagName === 'children' && this.childrenDeviceList.length === 0) {
          this.getProductData()
          this.handleRefresh();
        }
      },

      /** 监听详情页面显示状态*/
      detailedPageVisible(state) {
        // 详情页面关闭时清空日志页面数据
        if (!state) {
          this.childrenDeviceList = [];
        }
      },

      /** 实时设备状态监听 */
      deviceOnlineChange(data = {}) {

        const deviceId = data.deviceId;

        if (!deviceId) {
          return;
        }

        const index = this.childrenDeviceList.findIndex(data => data.id === deviceId);

        if (index === -1) {
          return;
        }

        // 更新设备状态数量
        this.updateDeviceStateCount();

        let row = this.childrenDeviceList[index];

        const type = data.type;

        if (type === 'ONLINE') {
          row.deviceState = 'online'
          this.$set(this.childrenDeviceList, index, row);
        }else if (type === 'OFFLINE') {
          row.deviceState = 'offline'
          this.$set(this.childrenDeviceList, index, row);
        }
      }

    },

    data() {
      return {
        //状态统计
        count: {},
        // 设备表格数据
        childrenDeviceList: [],
        // 全部子设备
        allChildrenDevice: [],
        //产品列表
        productList: [],
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id: null,
          deviceName: null,
          productId: null
        },
      }
    },
    methods: {

      /** 获取设备列表数据 */
      getList() {
        this.loading = true;
        this.queryParams.parentId = this.deviceDetailInfo.id;
        listDevice(this.queryParams).then(response => {
          this.childrenDeviceList = response.rows;
          this.total = response.total;
          this.loading = false
        });
      },

      /** 更新设备状态数量*/
      updateDeviceStateCount(){
        this.count = {
          amount: 0,
          offlineCount: 0,
          onlineCount: 0,
          notActiveCount: 0
        };
        // 获取设备状态的数量
        this.getAllChildrenDevice().then((data = []) => {
          this.count.amount = data.length;
          this.count.offlineCount = data.filter(childrenDevice => childrenDevice.deviceState === 'offline').length
          this.count.onlineCount = data.filter(childrenDevice => childrenDevice.deviceState === 'online').length
          this.count.notActiveCount = data.filter(childrenDevice => childrenDevice.deviceState === 'notActive').length
        });
      },

      /** 获取全部子设备 */
      getAllChildrenDevice() {
        return new Promise(resolve => {
          queryDevice({ parentId: this.deviceDetailInfo.id }).then(({ data = [] }) => {
            this.allChildrenDevice = data;
            resolve(data)
          });
        })
      },

      /** 获取产品数据 */
      getProductData() {
        queryProduct({ deviceType: 'childrenDevice' }).then(response => {
          this.productList = response.data
        });
      },

      /** 查看按钮的点击事件 */
      handleCheck(row) {
        // 传递数据给详情页面
        this.$store.commit('DEVICE_ID', row.id)
        // 返回设备详情页面
        this.$store.commit('TABS_ACTIVE_NAME', 'deviceDetails');
      },

      /** 绑定子设备按钮操作 */
      bindChildrenDevice(row) {
        this.$refs.bindChildrenDevice.handleUpdate(row)
      },

      /** 解除绑定子设备 */
      unbindChildrenDevice(row) {
        const ids = row.id || this.ids;
        this.$modal
          .confirm('是否确认要与设备"' + this.deviceDetailInfo.name + '"解绑吗？')
          .then(() => {
            return unbindChildrenDevice(ids).then(({code}) => {
              if (code === 200) {
                this.handleRefresh();
                this.$modal.msgSuccess('解绑成功')
              }
            })
          })
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList()
      },

      /** 刷新操作 */
      handleRefresh() {
        // 更新表格
        this.getList();
        // 更新设备状态数量
        this.updateDeviceStateCount()
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm');
        this.handleQuery()
      },

      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        selection.forEach(row => {
          if (row.publishState === 1) {
            this.$refs.deviceTable.toggleRowSelection(row)
          }
        });
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.$refs.childrenDeviceAddEdit.handleAdd()
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.$refs.childrenDeviceAddEdit.handleUpdate(row)
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal
          .confirm('是否确认删除id为"' + ids + '"的设备？')
          .then(() => {
            return delDevice(ids).then(({code}) => {
              if (code === 200) {
                this.handleRefresh();
                this.$modal.msgSuccess('删除成功')
              }
            })
          })
      },

      /** 启用禁用按钮操作 */
      handleEnableDisableStateChange(row) {
        let text = row.deviceState === 'notActive' ? '启用' : '禁用';
        this.$modal
            .confirm(`确认要${text}${row.deviceName}设备吗？`)
            .then(() => {
              if (row.deviceState === 'notActive') {
                deployDevice(row.id).then(() => {
                  this.handleRefresh();
                })
              } else {
                undeployDevice(row.id).then(() => {
                  this.handleRefresh();
                })
              }
            }).then(() => {
          this.$modal.msgSuccess(`${text}成功`)
        })
      },

      /** 激活设备点击事件 */
      batchDeployDevice() {

        let ids = this.ids;

        if (ids && ids.length > 0) {
          this.$modal
            .confirm('确定要启用选中的设备?')
            .then(() => {
              deployDevice(ids).then(() => {
                this.handleRefresh()
              })
            })
          return;
        }

        ids = this.allChildrenDevice.map(item => item.id);

        this.$modal
          .confirm('确定启用全部子设备？')
          .then(() => {
            deployDevice().then(() => {
              this.handleRefresh()
            })
          })
      },

      /** 同步设备状态 */
      handleSyncDeviceState() {

        let ids = this.ids;
        if (ids && ids.length > 0) {
          this.$modal
            .confirm('确定要同步选中的设备状态?')
            .then(() => {
              syncDeviceState(ids).then(({ data }) => {
                this.$modal.msgSuccess(`已完成，总数量:${data}`)
                this.handleRefresh()
              })
            })
          return;
        }

        ids = this.allChildrenDevice.map(item => item.id);

        this.$modal
          .confirm('确定同步全部子设备状态?')
          .then(() => {
            syncDeviceState(ids).then(({ data }) => {
              this.$modal.msgSuccess(`已完成，总数量:${data}`)
              this.handleRefresh()
            })
          })
      },

    }
  }
</script>

<style scoped>

</style>
